package sample.login.service;

import com.alibaba.fastjson.JSON;
import com.google.common.io.Files;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import sample.constants.FilesIndexConstants;
import sample.login.User;
import sample.utils.FileUtils;
import sample.utils.ResultBody;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * @author taowenchen
 */
@Service
public class LoginServiceImpl implements LoginService {

    Logger logger = LoggerFactory.getLogger(LoginServiceImpl.class);

    @Override
    public ResultBody login(User user) {

        final File file = new File(FileUtils.getFile() + String.format(FilesIndexConstants.ACCOUNT_FILE_DIR, user.getAccount() + ".dat"));
        if (!file.exists()) {
            return ResultBody.builder().status(false).msg("账户不存在").build();
        }

        try {
            final String password = Files.readFirstLine(file, StandardCharsets.UTF_8);
            if (!StringUtils.equals(user.getPassword(), password)) {
                return ResultBody.builder().status(false).msg("登录密码不正确").build();
            }
        } catch (IOException e) {
            return ResultBody.builder().status(false).msg("登录异常").build();
        }

        try {
            final File lastLoginFile = new File(FileUtils.getFile() + String.format(FilesIndexConstants.ACCOUNT_FILE_DIR, "lastlogin.dat"));
            if (!lastLoginFile.exists()) {
                lastLoginFile.createNewFile();
            }
            Files.write(JSON.toJSONString(user).getBytes(StandardCharsets.UTF_8),lastLoginFile);
        } catch (Exception e) {
            logger.warn("保存上次登录信息失败：", e);
        }


        return ResultBody.builder().status(true).msg("登录成功").build();


    }
}
